<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.clientId" placeholder="客户端ID" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-input v-model="listQuery.clientName" placeholder="客户端名称" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-input v-model="listQuery.clientSecret" placeholder="客户端秘钥" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加
      </el-button>
      <!-- <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        Export
      </el-button> -->
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="客户端ID" min-width="120px">
        <template slot-scope="{row}">
          <span class="link-type">{{ row.title }}</span>
          <el-tag>{{ row.clientId  }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="客户端名称" min-width="120px">
        <template slot-scope="{row}">
          <span class="link-type">{{ row.title }}</span>
          <el-tag>{{ row.clientName  }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="客户端秘钥" min-width="150px">
        <template slot-scope="{row}">
          <span class="link-type">{{ row.title }}</span>
          <el-tag>{{ row.clientSecret  }}</el-tag>
        </template>
      </el-table-column>
       <el-table-column label="备注" min-width="150px">
        <template slot-scope="{row}">
          <span class="link-type">{{ row.title }}</span>
          <span>{{ row.clientRemark  }}</span>
        </template>
      </el-table-column>
       <el-table-column label="修改人" min-width="80px">
        <template slot-scope="{row}">
          <span class="link-type">{{ row.title }}</span>
          <span>{{ row.updatedBy  }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改时间" width="200px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.updatedTime  }}</span>
        </template>
      </el-table-column>
       <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button type="primary" size="mini" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.current" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="100px" style="width: 500px; margin-left:50px;">
        <el-form-item label="ID" prop="id" style="display: none">
          <el-input v-model="temp.id"/>
        </el-form-item>
        <el-form-item label="客户端ID" prop="clientId">
          <el-input v-model="temp.clientId" />
        </el-form-item>
        <el-form-item label="客户端名称" prop="clientName">
          <el-input v-model="temp.clientName" />
        </el-form-item>
        <el-form-item label="客户端地址" prop="clientUrl">
          <el-input v-model="temp.clientUrl" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="temp.clientRemark" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" placeholder="Please input" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          清空
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>

    <el-dialog title="提示" :visible.sync="dialogDelVisible" width="30%" :before-close="handleClose">
      <span>确定需要删除<el-tag>{{temp.clientName}}</el-tag>吗？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogDelVisible = false">取消</el-button>
        <el-button type="primary" @click="delData">删除</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { pageList , createClient, updateClient, deleteClient } from '@/api/client'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination


export default {
  name: 'ComplexTable',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        current: 1,
        limit: 20,
        current:''
      },
      importanceOptions: [1, 2, 3],
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      temp: {
        id: '',
        clientId: '',
        clientId: '',
        clientName: '',
        clientRemark: '',
        clientUrl: '^(http|https)://.*'
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      dialogDelVisible: false,
      rules: {
        clientId: [{ required: true, message: 'type is required', trigger: 'change' }],
        clientName: [{ required: true, message: 'timestamp is required', trigger: 'change' }],
        clientUrl: [{ required: true, message: 'title is required', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      pageList(this.listQuery).then(response => {
        this.list = response.result.records
        this.total = response.result.total

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    resetTemp() {
      this.temp = {
        clientId: '',
        clientId: '',
        clientName: '',
        clientRemark: '',
        clientUrl: '^(http|https)://.*'
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          createClient(this.temp).then(() => {
            this.getList()
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Created Successfully',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          updateClient(tempData).then(() => {
            for (const v of this.list) {
              if (v.id === this.temp.id) {
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, this.temp)
                break
              }
            }
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Update Successfully',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleClose(done){
      done()
    },
    handleDelete(row) {
      this.dialogDelVisible = true
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'delete'
    },
     delData() {
      this.dialogDelVisible = false
      const tempData = Object.assign({}, this.temp)
      deleteClient(tempData).then(() => {
        this.getList()
        this.$notify({
          title: 'Success',
          message: 'Delete Successfully',
          type: 'success',
          duration: 2000
        })
      })
    },
    handleDownload() {
    },
  }
}
</script>
